package com.tanhua.dubbo.api.Impl;

import com.itheima.dubbo.api.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongoDb.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Author Pan Rundong
 * @Date 2023-03-07 13:07
 * @Desc 视频Api实现类
 */
@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    /**
     * 发布视频
     *
     * @param video
     * @return java.lang.String
     * @Author Pan Rundong
     */
    @Override
    public String save(Video video) {
        //1、设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(video);
        //3、返回对象id
        return video.getId().toHexString();
    }

    /**
     * 根据Vid查询Video
     *
     * @param vids
     * @return java.util.List<com.tanhua.model.mongoDb.Video>
     * @Author Pan Rundong
     */
    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pagesize
     * @return java.util.List<com.tanhua.model.mongoDb.Video>
     * @Author Pan Rundong
     */
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 视频分页查询
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    @Override
    public PageResult findVideosByPage(Integer page, Integer pagesize, Long uid) {
        // 1.设置查询用户
        Query query = Query.query(Criteria.where("userId").is(uid));
        // 2.计算对应count
        long count = mongoTemplate.count(query, Video.class);

        //3.设置分页条件
        query.limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //4.查询对应list
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        return new PageResult(page, pagesize, (int) count, videoList);
    }
}
